<?php

namespace App\Exceptions;

use Exception;
use Dingo\Api\Exception\ValidationHttpException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Exception $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof UnauthorizedHttpException) {
            return response()->json(['message' => $exception->getMessage(), 'code' => 401, 'status' => false]);
        }

        if ($exception instanceof ValidationHttpException) {
            $data = $exception->getErrors();
            $msg = collect($data)->first();
            if (is_array($msg)) {
                $msg = $msg[0];
            }

            return response()->json(['message' => $msg, 'code' => $exception->getCode(), 'status' => false]);
        }

        if ($exception instanceof TokenInvalidException || $exception instanceof TokenBlacklistedException) {
            return response()->json(['message' => trans('api.need_login'), 'code' => 401, 'status' => false]);
        }

        if ($exception instanceof HttpException) {
            return response()->json(['message' => $exception->getMessage(), 'code' => $exception->getCode(), 'status' => false]);
        }

        if ($request->wantsJson()) {
            return response()->json(['message' => $exception->getMessage(), 'code' => $exception->getCode(), 'status' => false]);
        }

        return parent::render($request, $exception);
    }
}
